package com.hula.onion.book.server.spider.platforms.elutongxin;

import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.LoginForm;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.model.AccountInfo;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by work on 2018/3/14.
 */
@Component
public class ELuTongXinSpiderHelper {

    public Map<String, Object> installCheckParams(LoginForm form) {
        Map<String, Object> map = new HashMap<>(1);
        map.put("userMobile", form.getUserName());
        return map;
    }

    /**
     * 组装请求参数
     *
     * @param form
     * @return
     */
    public Map<String, Object> installRequestParams(LoginForm form) {
        Map<String, Object> map = new HashMap<>(2);
        map.put("userMobile", form.getUserName());
        map.put("userPassword", form.getPassword());
        return map;
    }

    public boolean loginSuccess(String html) {
        try {
            Document document = Jsoup.parse(html);
            Element element = document.selectFirst("#loginerror");
            if (element != null) {
                return false;
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public CommonResponse parseAccountBalance(String html) {
        try {
            Document document = Jsoup.parse(html);
            Element element = document.selectFirst("div.invest-view");
            String amount = element.children().get(0)
                    .children().get(0).children().get(0).text();
            String totalInterest = element.children().get(1).children().get(0).text();
            AccountInfo accountInfo = new AccountInfo();
            accountInfo.setAmount(new BigDecimal(amount));
            accountInfo.setTotalIntrest(new BigDecimal(totalInterest));
            return new CommonResponse(accountInfo);
        } catch (Exception e) {
            return new CommonResponse(ResponseStatusEnum.QUERY_FAIL);
        }
    }

}
